package pl.edu.mimuw.irs.rcp.controller.part;

import org.eclipse.draw2d.BendpointConnectionRouter;
import org.eclipse.draw2d.ConnectionAnchor;
import org.eclipse.draw2d.ConnectionEndpointLocator;
import org.eclipse.draw2d.IFigure;
import org.eclipse.draw2d.Label;
import org.eclipse.draw2d.PolygonDecoration;
import org.eclipse.draw2d.PolylineConnection;
import org.eclipse.draw2d.PositionConstants;
import org.eclipse.gef.editparts.AbstractConnectionEditPart;
import org.eclipse.swt.SWT;
import org.eclipse.swt.graphics.Font;

import pl.edu.mimuw.irs.core.model.petrinet.Arc;
import pl.edu.mimuw.irs.rcp.view.figure.ChopboxHandleBoundsAnchor;
import pl.edu.mimuw.irs.rcp.view.figure.EllipseHandleBoundsAnchor;

/**
 * @author Jakub Rauch
 * Created on: 2009-05-18
 */
public class ArcEditPart extends AbstractConnectionEditPart {

	// *** Attributes

	// *** Methods
	
	@Override
	protected void createEditPolicies() {
		// TODO : edycja arc - trzeba dodac bendpoints
		
		
	}
	
	@Override
	protected ConnectionAnchor getSourceConnectionAnchor() {
		if (getSource() == null || !(getSource() instanceof INodeEditPart)) { 
			return super.getSourceConnectionAnchor();
		} else if (getSource() instanceof PlaceEditPart) {
			return new EllipseHandleBoundsAnchor(((INodeEditPart)getSource()).getFigure());
		} else {
			return new ChopboxHandleBoundsAnchor(((INodeEditPart)getSource()).getFigure());
		}
	}
	
	@Override
	protected ConnectionAnchor getTargetConnectionAnchor() {
		if (getTarget() == null || !(getTarget() instanceof INodeEditPart)) { 
			return super.getTargetConnectionAnchor();
		} else if (getTarget() instanceof PlaceEditPart) {
			return new EllipseHandleBoundsAnchor(((INodeEditPart)getTarget()).getFigure());
		} else {
			return new ChopboxHandleBoundsAnchor(((INodeEditPart)getTarget()).getFigure());
		}
	}
	
	protected IFigure createFigure()
	{
		PolylineConnection connection = (PolylineConnection)super.createFigure();
		connection.setConnectionRouter(new BendpointConnectionRouter());
		connection.setTargetDecoration(new PolygonDecoration());
		
		int weight = getArc().getWeight();
		if (weight > 1) {
			Label label = new Label(new Integer(getArc().getWeight()).toString());
			Font placeFont = new Font(null, "Arial", 8, SWT.NORMAL);
	
			label.setFont(placeFont);
			label.setTextAlignment(PositionConstants.CENTER);
	        label.setTextPlacement(PositionConstants.CENTER);
	        
	        ConnectionEndpointLocator locator = 
	            new ConnectionEndpointLocator(connection, true);
	        locator.setUDistance(5);
	        locator.setVDistance(5);
	        
	        connection.add(label, locator);
		}
		return connection;
	}
	
	protected Arc getArc() {
		return (Arc)getModel();
	}
}
